14. Exercise: Adapter Pattern

Exercise: Adapter Pattern

Remember that exercise last lesson, MergeShards.java?

Your coworker, who is a design patterns whiz, was glancing over that code during a code review and noticed that it opens many files at once. In order to increase the cleanliness of the code, she suggests using the Adapter Pattern to simplify that code and manage the opening and closing of all the shard files.

Your starter code for this exercise is the solution code to MergeShards.java, with the addition of a helper class, MultiFileReader.java, that you need to fill in. MultiFileReader implements the Closeable interface. Recall that any object that implements Closeable can be declared as a resource using the try-with-resources idiom. Where does the adapter pattern fit in? In this case, you are adapting your List<Path> of shard files to the Closeable interface to make the readers easier to manage.

  1. First, implement the MultiFileReader(List<Path> paths) constructor, which should create a list of BufferedReaders from the given paths. If any of the BufferedReaders throws an exception, be sure to close the readers you've already created!
  2. Next, implement the MultiFileReader#close() method, which should close all the BufferedReaders.
  3. When you are done implementing MultiFileReader, complete all the TODOs in MergeShards.java to use your new adapter! The new main method should look a lot cleaner!

Running the solution

Finally, if you want, you can rerun the shard merger to make sure it still works:

javac MergeShards.java
java MergeShards shards/ sorted.txt

TODO List

Task List:

Task Feedback:

Nice work!

Code

If you need a code on the https://github.com/udacity.

  • userCode:

    export PATH=/data/jdk-15.0.1/bin:$PATH
    export JAVA_HOME=/data/jdk-15.0.1/bin